'use client';

import React, { useState, useEffect } from 'react';
import { Layout } from '@/components/layout';
import { useApp } from '@/hooks';
import { generateRecommendations, getDiverseRecommendations } from '@/lib/recommendation';
import { Recommendation, ScheduleItem, TechPreference } from '@/types';
import { useRouter } from 'next/navigation';

const RecommendationsPage: React.FC = () => {
  const { state, setRecommendations, setUserSchedule } = useApp();
  const router = useRouter();
  const [recommendations, setLocalRecommendations] = useState<Recommendation[]>([]);
  const [selectedItems, setSelectedItems] = useState<string[]>([]);
  const [filterTag, setFilterTag] = useState<string>('all');
  const [sortBy, setSortBy] = useState<'score' | 'time' | 'rating'>('score');
  const [showDiverse, setShowDiverse] = useState(false);

  useEffect(() => {
    if (!state.userProfile) {
      router.push('/profile');
      return;
    }

    // 生成推荐
    const recs = showDiverse 
      ? getDiverseRecommendations(state.userProfile, 15)
      : generateRecommendations(state.userProfile, 15);
    
    setLocalRecommendations(recs);
    setRecommendations(recs);
  }, [state.userProfile, showDiverse, setRecommendations]); // eslint-disable-line react-hooks/exhaustive-deps

  // 筛选和排序推荐
  const filteredAndSortedRecommendations = recommendations
    .filter(rec => {
      if (filterTag === 'all') return true;
      return rec.agendaItem.tags.includes(filterTag as TechPreference);
    })
    .sort((a, b) => {
      switch (sortBy) {
        case 'score':
          return b.score - a.score;
        case 'time':
          return a.agendaItem.startTime.getTime() - b.agendaItem.startTime.getTime();
        case 'rating':
          return (b.agendaItem.rating || 0) - (a.agendaItem.rating || 0);
        default:
          return 0;
      }
    });

  // 获取所有可用的技术标签
  const availableTags = Array.from(
    new Set(recommendations.flatMap(rec => rec.agendaItem.tags))
  );

  // 处理选择项目
  const handleSelectItem = (itemId: string) => {
    setSelectedItems(prev => 
      prev.includes(itemId) 
        ? prev.filter(id => id !== itemId)
        : [...prev, itemId]
    );
  };

  // 添加到日程
  const handleAddToSchedule = () => {
    if (!state.userProfile) return;

    const selectedAgendaItems = recommendations
      .filter(rec => selectedItems.includes(rec.agendaItem.id))
      .map(rec => rec.agendaItem);

    const scheduleItems: ScheduleItem[] = selectedAgendaItems.map(item => ({
      id: `schedule-${item.id}`,
      agendaItem: item,
      priority: 'medium',
      notes: ''
    }));

    const userSchedule = {
      id: `schedule-${Date.now()}`,
      userId: state.userProfile.id,
      items: scheduleItems,
      createdAt: new Date(),
      updatedAt: new Date()
    };

    setUserSchedule(userSchedule);
    router.push('/schedule');
  };

  // 格式化时间
  const formatTime = (date: Date) => {
    return date.toLocaleString('zh-CN', {
      month: 'numeric',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  // 获取置信度颜色
  const getConfidenceColor = (confidence: number) => {
    if (confidence >= 0.8) return 'text-success';
    if (confidence >= 0.6) return 'text-warning';
    return 'text-muted';
  };

  if (!state.userProfile) {
    return (
      <Layout>
        <div className="container mx-auto px-4 py-20 text-center">
          <div className="text-6xl mb-4">🤔</div>
          <h2 className="text-2xl font-bold text-foreground mb-4">请先完成用户画像构建</h2>
          <p className="text-muted mb-8">我们需要了解您的技术偏好和参会目标，才能为您推荐合适的日程。</p>
          <button 
            onClick={() => router.push('/profile')}
            className="btn btn-primary px-8 py-3"
          >
            开始构建画像
          </button>
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <div className="container mx-auto px-4 py-8">
        {/* 页面标题 */}
        <div className="text-center mb-12">
          <h1 className="text-4xl font-bold text-foreground mb-6">
            🎯 为您推荐的个性化日程
          </h1>
          <p className="text-xl text-muted max-w-4xl mx-auto leading-relaxed">
            基于您的技术偏好和参会目标，我们精心挑选了最适合您的会议日程
          </p>
        </div>

        {/* 筛选和排序控件 */}
        <div className="bg-surface rounded-xl p-8 mb-10 border border-border shadow-sm">
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6 items-end">
            <div>
              <label className="block text-lg font-semibold text-foreground mb-3">
                技术领域筛选
              </label>
              <select
                value={filterTag}
                onChange={(e) => setFilterTag(e.target.value)}
                className="w-full p-3 text-lg border-2 border-border rounded-lg bg-surface hover:border-primary/50 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all duration-200"
              >
                <option value="all">全部领域</option>
                {availableTags.map(tag => (
                  <option key={tag} value={tag}>
                    {tag.replace('_', ' ').toUpperCase()}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-lg font-semibold text-foreground mb-3">
                排序方式
              </label>
              <select
                value={sortBy}
                onChange={(e) => setSortBy(e.target.value as 'score' | 'time' | 'rating')}
                className="w-full p-3 text-lg border-2 border-border rounded-lg bg-surface hover:border-primary/50 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all duration-200"
              >
                <option value="score">推荐评分</option>
                <option value="time">开始时间</option>
                <option value="rating">用户评分</option>
              </select>
            </div>

            <div>
              <label className="block text-lg font-semibold text-foreground mb-3">
                推荐策略
              </label>
              <div className="flex space-x-3">
                <button
                  onClick={() => setShowDiverse(false)}
                  className={`btn ${!showDiverse ? 'btn-primary' : 'btn-secondary'} flex-1 py-3`}
                >
                  精准匹配
                </button>
                <button
                  onClick={() => setShowDiverse(true)}
                  className={`btn ${showDiverse ? 'btn-primary' : 'btn-secondary'} flex-1 py-3`}
                >
                  多样化
                </button>
              </div>
            </div>

            <div>
              <label className="block text-lg font-semibold text-foreground mb-3">
                已选择 ({selectedItems.length})
              </label>
              <button
                onClick={handleAddToSchedule}
                disabled={selectedItems.length === 0}
                className="btn btn-primary w-full py-3 text-lg font-semibold disabled:opacity-50 disabled:cursor-not-allowed"
              >
                添加到日程
              </button>
            </div>
          </div>
        </div>

        {/* 推荐列表 */}
        <div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
          {filteredAndSortedRecommendations.map((recommendation) => {
            const { agendaItem, score, reasons, confidence } = recommendation;
            const isSelected = selectedItems.includes(agendaItem.id);

            return (
              <div
                key={agendaItem.id}
                className={`
                  card card-interactive border-2 transition-all duration-200 p-8 min-h-[400px]
                  ${isSelected ? 'border-primary bg-primary/5 shadow-lg' : 'border-border hover:shadow-lg'}
                `}
                onClick={() => handleSelectItem(agendaItem.id)}
              >
                {/* 头部信息 */}
                <div className="flex items-start justify-between mb-6">
                  <div className="flex-1 pr-4">
                    <h3 className="text-xl font-bold text-foreground mb-3 leading-tight">
                      {agendaItem.title}
                    </h3>
                    <div className="flex items-center space-x-6 text-muted">
                      <span className="flex items-center space-x-1">
                        <span>📅</span>
                        <span>{formatTime(agendaItem.startTime)}</span>
                      </span>
                      <span className="flex items-center space-x-1">
                        <span>📍</span>
                        <span>{agendaItem.location}</span>
                      </span>
                      <span className="flex items-center space-x-1">
                        <span>⭐</span>
                        <span>{agendaItem.rating || 'N/A'}</span>
                      </span>
                    </div>
                  </div>
                  
                  {/* 选择状态 */}
                  <div className={`
                    w-7 h-7 rounded-full border-2 flex items-center justify-center transition-all duration-200
                    ${isSelected ? 'border-primary bg-primary shadow-md' : 'border-border hover:border-primary/50'}
                  `}>
                    {isSelected && (
                      <svg className="w-5 h-5 text-white" fill="currentColor" viewBox="0 0 20 20">
                        <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                      </svg>
                    )}
                  </div>
                </div>

                {/* 推荐评分和置信度 */}
                <div className="flex items-center justify-between mb-6 p-4 bg-background/50 rounded-lg">
                  <div className="flex items-center space-x-6">
                    <div>
                      <span className="text-muted">推荐评分: </span>
                      <span className="font-bold text-lg text-primary">
                        {Math.round(score * 100)}%
                      </span>
                    </div>
                    <div>
                      <span className="text-muted">置信度: </span>
                      <span className={`font-bold text-lg ${getConfidenceColor(confidence)}`}>
                        {Math.round(confidence * 100)}%
                      </span>
                    </div>
                  </div>
                  
                  {agendaItem.isKeynote && (
                    <span className="bg-gradient-primary text-white px-4 py-2 rounded-full text-sm font-semibold shadow-md">
                      主题演讲
                    </span>
                  )}
                </div>

                {/* 会议描述 */}
                <p className="text-muted mb-6 line-clamp-3 leading-relaxed">
                  {agendaItem.description}
                </p>

                {/* 技术标签 */}
                <div className="flex flex-wrap gap-3 mb-6">
                  {agendaItem.tags.slice(0, 3).map(tag => (
                    <span
                      key={tag}
                      className="bg-primary/10 text-primary px-3 py-2 rounded-full text-sm font-semibold"
                    >
                      {tag.replace('_', ' ').toUpperCase()}
                    </span>
                  ))}
                  {agendaItem.tags.length > 3 && (
                    <span className="text-sm text-muted font-medium">
                      +{agendaItem.tags.length - 3} 更多
                    </span>
                  )}
                </div>

                {/* 推荐理由 */}
                <div className="space-y-2 mb-6">
                  <h4 className="font-bold text-foreground">推荐理由:</h4>
                  {reasons.slice(0, 2).map((reason, index) => (
                    <div key={index} className="text-muted flex items-center space-x-3">
                      <span className="w-2 h-2 bg-primary rounded-full flex-shrink-0"></span>
                      <span className="leading-relaxed">{reason.description}</span>
                    </div>
                  ))}
                </div>

                {/* 演讲者信息 */}
                {agendaItem.speakers.length > 0 && (
                  <div className="pt-4 border-t border-border">
                    <div className="text-muted">
                      <span className="font-semibold">演讲者: </span>
                      <span>{agendaItem.speakers.map(s => s.name).join(', ')}</span>
                    </div>
                  </div>
                )}
              </div>
            );
          })}
        </div>

        {/* 空状态 */}
        {filteredAndSortedRecommendations.length === 0 && (
          <div className="text-center py-32">
            <div className="text-8xl mb-6">😔</div>
            <h3 className="text-2xl font-bold text-foreground mb-4">
              没有找到匹配的推荐
            </h3>
            <p className="text-lg text-muted">
              请尝试调整筛选条件或修改您的用户画像
            </p>
          </div>
        )}
      </div>
    </Layout>
  );
};

export default RecommendationsPage;